package controller;

import helper.Balance;
import helper.Calendr;
import helper.Formatter;
import helper.UserSession;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;

import databeans.Customer;
import databeans.Employee;
import databeans.Fund;
import databeans.FundHistory;
import databeans.Payment;
import databeans.Transaction;

import model.CustomerDAO;
import model.Model;
import model.PaymentDAO;
import model.TransactionDAO;

public class CustomerRequestCheckAction extends Action {

	private PaymentDAO paymentDAO;
	private CustomerDAO customerDAO;
	private TransactionDAO transactionDAO;

	public CustomerRequestCheckAction(Model model) {
		paymentDAO = model.getPaymentDAO();
		customerDAO = model.getCustomerDAO();
		transactionDAO = model.getTransactionDAO();
	}

	public String getName() {
		return "customerRequestCheck.do";
	}

	@Override
	public String perform(HttpServletRequest request) {

		// set pages
		String loginPage = "customer/customer-login.jsp";
		String originPage = "customer/request-check.jsp";
		String successPage = originPage;
		//String successPage = "customer/view-payment-history.jsp";
		
		Customer customer = null;
		Employee employee = null;
		
		//Errors
		List<String> errors = new ArrayList<String>();
	    List<String> messages = new ArrayList<String>();
		
	    //define the error and message
        request.setAttribute("errors", errors);
        request.setAttribute("messages", messages);
        request.setAttribute("page", "req-check");
        
	    //check if customer has actually logged in
        employee = UserSession.getLoggedInEmployee(request);
        if (employee != null) {
            UserSession.removeEmployeeFromSession(request);
            errors.add("This section is closed for employee");
            return loginPage ;
        }
        
        //check if customer has actually logged in
        customer = UserSession.getLoggedInCustomer(request);
        if (customer == null) {
            errors.add("You need to log in");
            return loginPage;
        }
        
        long customerAvailableCash = 000;
        
        try {
        	customerAvailableCash = Balance.getCustomerAvailableCash(customer);            
        } catch (DAOException e1) {
            errors.add("Customer available balance could not be resolved");
            return originPage;
        }

        request.setAttribute("cashBalance", Formatter.prepCashToView(customerAvailableCash));
           
        if(customerAvailableCash<=0)
        {
        	errors.add("You do not have sufficient Cash Balance to request a Check. Please try again later.");
            return originPage;
        }
        //Get Params
		String requestType = request.getParameter("Submit");
        String customerID = String.valueOf(customer.getCustomerID());        
        String amount = request.getParameter("txtAmount");
        
        System.out.println("===============>> check Amount = " + amount);
        //Set Attributes 
        request.setAttribute("txtAmount", amount);
        
        System.out.println("requestType= " + requestType);
        
        if (requestType == null) {
            messages.add("Enter the amount you wish to withdraw from your account");
            request.setAttribute("cashBalance", Formatter.prepCashToView(customerAvailableCash));
            return originPage;     
        }
        
        //validate the input
        
        if (customerID.trim().equals("")) {
            //messages.add("Customer ID must be provided");
            errors.add("System Error. Could not fetch Customer data.");
            return originPage;
        }
        
        if (amount.trim().equals("")) {
            errors.add("Please enter a value for the Check Amount");
            return originPage;
        }
        

        //check if double value inputted is A double
        if (!Formatter.isDouble(amount)){
            //messages.add("You must input a number in amount field");
            errors.add("Invalid input in Amount field. Please check.");
            return originPage;
        }
        
        //check if double has 2 decimal place
        if(Formatter.numberOfDecimal(amount)>2) {
            messages.add("CFA only tracks amount up to two decimal place. Please reenter the amount");
            errors.add("Accuracy could not be captured");
            return originPage;
        }
        
        if (Double.parseDouble(amount) <= 0) {
            errors.add("Please enter a valid Check Amount");
            return originPage;
        }
         
     	try{
            if(Formatter.prepCashFromView(amount) > customerAvailableCash)
            {
            	errors.add("The requested amount is greater than your cash balance.");
            	return originPage;
            }
        } catch (NumberFormatException e1) {
            errors.add("Cash could not be retrieved. Please check");
            return originPage;
        }
        
        
        try {

            Payment tempTrans = new Payment();
            tempTrans.setCustomerID(Integer.parseInt(customerID));
            tempTrans.setSubmitDate(Calendr.getTodaysDate());
            tempTrans.setTransactionType(Transaction.CHECK_REQUEST);
            tempTrans.setAmount(Formatter.prepCashFromView(amount));
            tempTrans.setExecuted(false);
            //push those transaction object into database
            paymentDAO.create(tempTrans);
            
            

            
            //refresh customer available cash
            try {
                customerAvailableCash = Balance.getCustomerAvailableCash(customer);            
            } catch (DAOException e1) {
                errors.add("Customer available balance could not be resolved");
                return originPage;
            }

            request.setAttribute("cashBalance", Formatter.prepCashToView(customerAvailableCash));
               
            // Attach (this copy of) the logged in employee bean to the session
            HttpSession session = request.getSession(true); 
            session.setAttribute("customer", customer );
            
            //set the welcome message

            messages.add("Your Check Request of $ " + Formatter.prepCashToView(tempTrans.getAmount()) + " has been placed succesfully");

            return successPage;

        } catch (Exception e) {
            errors.add("Unable to process your request. Please try again later");
            return originPage;
        }
        
	}
	
}
